import util from '@/common/util';
import http from '@/common/http.js';
import {
	Websocket,
	Cmd
} from './websocket.js'
/**
 * websocket即时聊天工具。
 * 事件：online，当获得服务器在线人数时候触发
 */
class WebsocketApp extends Websocket {
	constructor(channel = "", msgHanders = [], eventHanders = []) {
		super({
			heartCheck: true,
			isReconnection: true
		});
		this.channel = channel;
		this.websocketId = ""
		this.online = 0;
		this.msgHanders = msgHanders;
		this.eventHanders = eventHanders;
		this.channelMsgTimer=null;
		//先关闭掉
		this.close() 
		this.init()
	}
	init() {
		// 建立连接s
		var that = this;
		that.addEventHandler('onOpen', function() {
			//订阅频道  
			if (that.channel) {
				that.joinChannel(that.channel);
			}
		});
		if (that.eventHanders) {
			//添加事件处理器
			that.eventHanders.forEach(function(e, i) {
				that.addEventHandler(e.event, e.hander);
			});
		}
		if (that.msgHanders) {
			//添加消息处理器
			that.msgHanders.forEach(function(e, i) {
				that.addMsgHandler(e.cmd, e.hander);
			});
		}		

		//初始化weosocket
		//const wsuri = "ws://127.0.0.1:8080";
		http.postForm('/api/ws/pre-connect', {
				websocketId: ""
			})
			.then(res => {
				var url = res.data.server;
				that.websocketId = res.data.websocketId;
				that.connect(url);//为啥要连接两次/
				//that.connect(url);
			})
			.catch(e => console.log(e));
	}
	/**
	 * @param {Object} channel 频道
	 * @param {Object} msg 消息对象，json对象的字符串格式,通过Cmd生成
	 */
	SendChannelMsg(channel, msg, callback) {
		var that=this
		if (!this.websocketId) {
			console.error("websocketId can not null,1m later ageing")
			that.channelMsgTimer=setTimeout(function(){
				 that.SendChannelMsg(channel, msg, callback) 				 
			},1000)
			return;
		}else{
			clearTimeout(that.channelMsgTimer)
		}
		http.postForm('/api/ws/send-channelmsg', {
				websocketId: this.websocketId,
				channel: channel,
				msg: msg
			})
			.then(res => {
				//console.log(res.data);
				callback && callback(res.data);
			})
			.catch(e => console.log(e));
	}
	/**
	 * 订阅频道
	 * @param {Object} e
	 */
	joinChannel(channel) {
		var that=this
		if (!this.websocketId) {
			console.error("websocketId can not null,1m later ageing")
			that.joinChannelTimer=setTimeout(function(){
				 that.joinChannel(channel)
			},1000)
			return;
		}else{
			clearTimeout(that.joinChannelTimer)
		}
		http.postForm('/api/ws/join-channel', {
				websocketId: this.websocketId,
				channel: channel
			})
			.then(res => {
				
				//console.log(res.data);
				/* that.SendChannelMsg(channel, Cmd.hello(channel), function() {
					that.getChannelOnlineCount(channel).then(res => {
						if (that._eventHandler['online'] && that._eventHandler['online'].length > 0) {
							that._eventHandler['online'].forEach(function(e, i) {
								e(res.data)
							});
						}
						//that.online = res.data;
					});
				}); */
				console.log(`订阅频道${channel}成功`);
			})
			.catch(e => console.log(e));
	}
	leaveChan(channel) {
		var that=this
		if (!this.websocketId) {
			console.error("websocketId can not null,1m later ageing")
			that.leaveChanTimer=setTimeout(function(){
				 that.joinChannel(channel)
			},1000)
			return;
		}else{
			clearTimeout( that.leaveChanTimer)
		}
		var that = this;
		http.postForm('/api/ws/leave-channel', {
				websocketId: this.websocketId,
				channel: channel
			})
			.then(res => {
				//console.log(res.data);
				/* that.SendChannelMsg(channel, Cmd.hello(channel), function() {
					that.getChannelOnlineCount(channel).then(res => {
						if (that._eventHandler['online'] && that._eventHandler['online'].length > 0) {
							that._eventHandler['online'].forEach(function(e, i) {
								e(res.data)
							});
						}
						//that.online = res.data;
					});
				}); */
				console.log(`取消频道${channel}成功`);
			})
			.catch(e => console.log(e));
	}
	getChannelOnlineCount(channel) {
		var that = this;
		return http.postForm('/api/ws/get-channelonline-count', {
			channel: channel || that.channel
		})
		/* .then(res => {
			that.$emit('onlineCount', res.data);
			//console.error(res)
			//that.online = res.data;
		})
		.catch(e => console.log(e)); */
	}
	getCmdMsg(cmd, data, channel, sender) {
		return Cmd.getCmdMsg(cmd, data, channel, sender);
	}
	getCmd() {
		return Cmd;
	}
}

export function mywebsocket(channel, msgHanders, eventHanders) {
	return new WebsocketApp(channel, msgHanders, eventHanders)
}
